package com.atguigu.chapter02;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.*;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/7/14 10:11
 */
public class Flink01_Batch_WC {
    public static void main(String[] args) throws Exception {
        // 1. 创建执行环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        // 2. 从source读取数据得到DataSet
        DataSource<String> source = env.readTextFile("input/words.txt");
        // 3. 对数据集做各种操作
        FlatMapOperator<String, String> wordsSet = source
            .flatMap(new FlatMapFunction<String, String>() {
                @Override
                public void flatMap(String line,
                                    Collector<String> out) throws Exception {
                    String[] data = line.split(" ");
                    for (String word : data) {
                        out.collect(word);
                    }
                }
            });
        
        MapOperator<String, Tuple2<String, Long>> wordAndOneSet = wordsSet.map(new MapFunction<String, Tuple2<String, Long>>() {
            @Override
            public Tuple2<String, Long> map(String word) throws Exception {
                return Tuple2.of(word, 1L);
            }
            
        });
        
        UnsortedGrouping<Tuple2<String, Long>> groupedSet = wordAndOneSet.groupBy(0);
        
        AggregateOperator<Tuple2<String, Long>> result = groupedSet.sum(1);
        
        // 4. 输出结果
        result.print();
        
    }
}
/*
spark:
    1.先创建SparkContext
    2. 从数据源读取数据得到一个RDD
    3. 对RDD做各种转换操作
    4. 行动算子
    5. 启动SparkContext
 */